#!/usr/bin/env python
# encoding: utf-8

import os
import re
import sys
import json
import glob
import time
import argparse
import zipfile

"""
@version: V1.0.0
@author: MQjehovah
@license: MIT
@contact: mqjehovah@hotmail.com
@site: www.mqgeek.com
@file: main.py
@time: 2017年9月20日 11:10:16
"""


def main(args):
    pass


def init_func(args):
    "初始化mq文件"
    if not os.path.exists(os.getcwd() + os.sep + "mq.json"):
        mqobj = {}
        mqobj['name'] = input("name?:")
        mqobj['author'] = input("author?:")
        mqobj['description'] = input("description?:")
        mqobj['license'] = input("license?:")
        mqobj['script'] = {}
        mqobj['dependencies'] = {}
        fp = open("mq.json", 'w', encoding='utf-8')
        fp.write(json.dumps(mqobj, indent=4, sort_keys=True, ensure_ascii=False))
        fp.close()
        print("init done")
    else:
        print("already init")


def install_func(args):
    "安装定义的第三方拓展文件"
    mqjson = open('mq.json', encoding='utf-8').read()
    mqobj = json.loads(mqjson)
    for item in mqobj['dependencies']:
        outpath = os.getcwd() + os.sep + item
        url = mqobj['dependencies'][item]
        print(outpath)
        print(url)
        os.system("git clone %s %s" % (url, outpath))
        delete_path(outpath + os.sep + ".git")  # 递归删除文件夹


def create_func(args):
    "创建项目命令，通过导入github项目完成项目初始化"
    if not args.o:
        args.o = os.getcwd()
    if args.m:  # 创建模块
        def render(match):
            str = match.group(1)
            if str == 'name':
                return args.name
            elif str == 'NAME':
                return args.name.upper()
            elif str == 'date':
                return time.strftime("%Y/%m/%d")
            else:
                return str
        if not os.path.exists(args.o):
            os.mkdir(args.o)
        all_text = open(sys.path[0] + '/templates/template.c').read()
        all_text = re.sub("{{(\w+)}}", render, all_text)
        file_ptr = open('%s/%s.c' % (args.o, args.name), 'w')
        file_ptr.write(all_text)
        file_ptr.close()
        all_text = open(sys.path[0] + '/templates/template.h').read()
        all_text = re.sub("{{(\w+)}}", render, all_text)
        file_ptr = open('%s/%s.h' % (args.o, args.name), 'w')
        file_ptr.write(all_text)
        file_ptr.close()
        return
    # 创建项目
    os.system("git clone git@github.com:%s.git %s" % (args.name, args.o))
    delete_path(args.o + os.sep + ".git")  # 递归删除文件夹


def run_func(args):
    "运行命令，执行mq文件中预定义的一些命令"
    mqjson = open('mq.json', encoding='utf-8').read()
    mqobj = json.loads(mqjson)
    if args.command in mqobj['script']:
        os.system(mqobj['script'][args.command])


def UnzipToPath(fn, op):
    "解压zip文件"
    f = zipfile.ZipFile(fn, 'r')
    for file in f.namelist():
        f.extract(file, op)


def delete_path(filePath):
    "完全删除一个文件夹"
    if os.path.exists(filePath):
        for fileList in os.walk(filePath):
            for name in fileList[2]:
                os.chmod(os.path.join(
                    fileList[0], name),  __import__("stat").S_IWRITE)
                os.remove(os.path.join(fileList[0], name))
        __import__("shutil").rmtree(filePath)
        return "delete ok"
    else:
        return "no filepath"


if __name__ == "__main__":
    parser = argparse.ArgumentParser(prog='mq', description='mq tool')
    subparsers = parser.add_subparsers(title='subcommands', help='commands')
    # 初始化子命令
    init_parser = subparsers.add_parser('init', help='init mq project')
    init_parser.set_defaults(func=init_func)
    # 安装子命令
    install_parser = subparsers.add_parser(
        'install', help='install vendor project')
    install_parser.set_defaults(func=install_func)
    # 创建子命令
    create_parser = subparsers.add_parser('create', help='create sub command')
    create_parser.add_argument('name', help='project name')
    create_parser.add_argument(
        '-m', help='create a stm32 module', action="store_true")
    create_parser.add_argument('-o', help='clone to path')
    create_parser.set_defaults(func=create_func)
    # 运行子命令
    run_parser = subparsers.add_parser(
        'run', help='run a script defined in mq.json')
    run_parser.add_argument('command', help='create a model')
    run_parser.set_defaults(func=run_func)

    args = parser.parse_args()
    args.func(args)
